/*
 *  Copyright@2024 河北智胜物语科技有限公司 保留所有权利
 */
package org.dromara.third.auth.service.impl;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.dromara.common.core.domain.R;
import org.dromara.common.core.exception.BusinessServiceException;
import org.dromara.third.auth.beans.constans.Constants;
import org.dromara.third.auth.beans.constans.ExceptionEnum;
import org.dromara.third.auth.config.AuthConfig;
import org.dromara.third.auth.domain.vo.AuthCompanyInfoVo;
import org.dromara.third.auth.service.AuthenticationService;
import org.dromara.third.auth.service.IAuthCompanyInfoService;
import org.dromara.third.auth.util.SignatureUtils;
import org.dromara.third.auth.vo.TokenRequest;
import org.dromara.third.auth.vo.TokenResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 鉴权业务实现类
 *
 * @author admin
 * @date 2020/7/13 17:01
 */
@Slf4j
@Service
@NoArgsConstructor
public class AuthenticationServiceImpl implements AuthenticationService {

    @Autowired
    private IAuthCompanyInfoService authCompanyInfoService;

    @Autowired
    private AuthConfig authConfig;

    @Override
    public TokenResponse getToken(TokenRequest tokenRequest) {
        //验签
        String appId = tokenRequest.getAppId();
        String timestamp = tokenRequest.getTimestamp();
        String digest = tokenRequest.getDigest().replace(" ","+");
        String queryString = tokenRequest.toString();
        //查询企业信息
        AuthCompanyInfoVo authCompanyInfoVo = authCompanyInfoService.selectByAppId(Long.valueOf(appId));
        if (null == authCompanyInfoVo) {
            throw new BusinessServiceException(ExceptionEnum.AuthException02.getCode(), ExceptionEnum.AuthException02.getMessage());
        }
        String accessKeyId = authCompanyInfoVo.getSecret();
        String sign = SignatureUtils.getAuthorization(appId, accessKeyId, queryString, "GET", timestamp);
        if (!digest.equals(sign)) {
            throw new BusinessServiceException(ExceptionEnum.AuthException03.getCode(), ExceptionEnum.AuthException03.getMessage());
        }
        //生成token
        long exp = System.currentTimeMillis() + authConfig.getExpTime();//过期时间为1小时
        JwtBuilder builder = Jwts.builder().setId(appId)
                .setSubject(authCompanyInfoVo.getEnterpriseName())
                .setIssuedAt(new Date())
                .signWith(SignatureAlgorithm.HS256, authConfig.getPrivateKey())
                .setExpiration(new Date(exp))
                .claim(Constants.COMPANY_CODE, authCompanyInfoVo.getCompanyCode());
        String accessToken = builder.compact();
        log.info("返回token：{}", accessToken);
        return TokenResponse.builder().accessToken(accessToken).expiresIn(String.valueOf(authConfig.getExpTime() / 1000)).build();
    }

    @Override
    public R<String> checkToken(String token) {
        try {
            //解析token
            Claims claims = Jwts.parser().setSigningKey(authConfig.getPrivateKey()).parseClaimsJws(token).getBody();
            log.info("id:" + claims.getId());
            log.info("subject:" + claims.getSubject());
            log.info("companyCode:" + claims.get("companyCode"));
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy‐MM‐dd hh:mm:ss");
            log.info("签发时间:" + sdf.format(claims.getIssuedAt()));
            log.info("过期时 间:" + sdf.format(claims.getExpiration()));
            log.info("当前时间:" + sdf.format(new Date()));
            return R.ok((String) claims.get("companyCode"));
        } catch (Exception e) {
            return R.fail(ExceptionEnum.AuthException04.getMessage());
        }
    }


}
